<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="page-title">轮回管理</h1>
        <div class="breadcrumb-container">
          <router-link to="/" class="link link-hover">首页</router-link>
          <span class="mx-2">/</span>
          <span>轮回管理</span>
        </div>
      </div>
      <div class="btn-group">
        <button class="btn btn-primary gap-2" @click="handleNewReincarnation">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v2H7a1 1 0 100 2h2v2a1 1 0 102 0v-2h2a1 1 0 100-2h-2V7z" clip-rule="evenodd" />
          </svg>
          新增轮回
        </button>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- 六道轮回图 -->
      <div class="card bg-base-100 shadow-lg">
        <div class="card-body">
          <h2 class="card-title">六道轮回</h2>
          <div class="relative aspect-square">
            <!-- 轮回圆盘 -->
            <div
              class="absolute inset-0 rounded-full border-4 border-primary/20"
              :style="{
                transform: `rotate(${wheelRotation}deg)`,
                transition: 'transform 1s cubic-bezier(0.4, 0, 0.2, 1)',
              }"
            >
              <!-- 六道分割线 -->
              <div v-for="(realm, index) in realms" :key="realm.name" class="absolute inset-0">
                <div
                  class="absolute top-0 left-1/2 h-1/2 w-0.5 origin-bottom"
                  :style="{
                    transform: `rotate(${index * 60}deg)`,
                    backgroundColor: realm.color,
                  }"
                ></div>
                <!-- 道名 -->
                <div
                  class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2"
                  :style="{
                    transform: `rotate(${index * 60}deg) translateY(-120px) rotate(-${index * 60}deg)`,
                  }"
                >
                  <div
                    class="text-center p-2 rounded-lg"
                    :class="currentRealm === realm.name ? 'bg-primary text-primary-content' : ''"
                  >
                    <div class="font-bold">{{ realm.name }}</div>
                    <div class="text-sm opacity-80">{{ realm.count }}魂</div>
                  </div>
                </div>
              </div>
              <!-- 中心点 -->
              <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-16 h-16 rounded-full bg-primary flex items-center justify-center text-primary-content font-bold text-xl">
                轮回
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 待轮回魂魄 -->
      <div class="card bg-base-100 shadow-lg">
        <div class="card-body">
          <h2 class="card-title mb-4">待轮回魂魄</h2>
          <div class="overflow-x-auto">
            <table class="table">
              <thead>
                <tr>
                  <th>魂魄ID</th>
                  <th>前世</th>
                  <th>功德值</th>
                  <th>待转生道</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="soul in souls" :key="soul.id">
                  <td class="font-mono text-sm">{{ soul.id }}</td>
                  <td>{{ soul.previousLife }}</td>
                  <td>
                    <div class="flex items-center gap-2">
                      <div class="radial-progress" :style="{ '--value': soul.merit, '--size': '2rem' }">
                        {{ soul.merit }}
                      </div>
                      <span>功德</span>
                    </div>
                  </td>
                  <td>
                    <div class="badge" :class="getRealmBadgeClass(soul.nextRealm)">
                      {{ soul.nextRealm }}
                    </div>
                  </td>
                  <td>
                    <div class="badge" :class="getStatusBadgeClass(soul.status)">
                      {{ getStatusLabel(soul.status) }}
                    </div>
                  </td>
                  <td>
                    <div class="btn-group">
                      <button class="btn btn-ghost btn-sm" @click="handleEdit(soul)">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                          <path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
                        </svg>
                      </button>
                      <button class="btn btn-ghost btn-sm" @click="handleReincarnate(soul)">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                          <path fill-rule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clip-rule="evenodd" />
                        </svg>
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 分页 -->
          <div class="flex justify-between items-center mt-4">
            <div class="text-sm text-base-content/60">
              共 {{ total }} 条记录
            </div>
            <div class="join">
              <button class="join-item btn btn-sm" :disabled="currentPage === 1" @click="handlePageChange(currentPage - 1)">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                  <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" />
                </svg>
              </button>
              <button class="join-item btn btn-sm">{{ currentPage }} / {{ totalPages }}</button>
              <button class="join-item btn btn-sm" :disabled="currentPage === totalPages" @click="handlePageChange(currentPage + 1)">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                  <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 轮回记录 -->
    <div class="card bg-base-100 shadow-lg mt-6">
      <div class="card-body">
        <h2 class="card-title mb-4">轮回记录</h2>
        <div class="overflow-x-auto">
          <table class="table">
            <thead>
              <tr>
                <th>记录ID</th>
                <th>魂魄ID</th>
                <th>前世</th>
                <th>今世</th>
                <th>轮回时间</th>
                <th>执行人</th>
                <th>状态</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="record in records" :key="record.id">
                <td class="font-mono text-sm">{{ record.id }}</td>
                <td class="font-mono text-sm">{{ record.soulId }}</td>
                <td>{{ record.previousLife }}</td>
                <td>{{ record.nextLife }}</td>
                <td>{{ formatDate(record.time) }}</td>
                <td>{{ record.operator }}</td>
                <td>
                  <div class="badge" :class="getStatusBadgeClass(record.status)">
                    {{ getStatusLabel(record.status) }}
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <dialog ref="editDialog" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg mb-4">{{ isEdit ? '编辑轮回' : '新增轮回' }}</h3>
        <form @submit.prevent="handleSubmit" class="space-y-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">魂魄ID</span>
            </label>
            <input
              type="text"
              v-model="form.soulId"
              placeholder="请输入魂魄ID"
              class="input input-bordered"
              :class="{ 'input-error': errors.soulId }"
            />
            <label class="label" v-if="errors.soulId">
              <span class="label-text-alt text-error">{{ errors.soulId }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">前世</span>
            </label>
            <input
              type="text"
              v-model="form.previousLife"
              placeholder="请输入前世"
              class="input input-bordered"
              :class="{ 'input-error': errors.previousLife }"
            />
            <label class="label" v-if="errors.previousLife">
              <span class="label-text-alt text-error">{{ errors.previousLife }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">功德值</span>
            </label>
            <input
              type="number"
              v-model="form.merit"
              placeholder="请输入功德值"
              class="input input-bordered"
              :class="{ 'input-error': errors.merit }"
            />
            <label class="label" v-if="errors.merit">
              <span class="label-text-alt text-error">{{ errors.merit }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">待转生道</span>
            </label>
            <select
              v-model="form.nextRealm"
              class="select select-bordered"
              :class="{ 'select-error': errors.nextRealm }"
            >
              <option value="">请选择</option>
              <option v-for="realm in realms" :key="realm.name" :value="realm.name">
                {{ realm.name }}
              </option>
            </select>
            <label class="label" v-if="errors.nextRealm">
              <span class="label-text-alt text-error">{{ errors.nextRealm }}</span>
            </label>
          </div>
        </form>
        <div class="modal-action">
          <button class="btn btn-ghost" @click="closeDialog">取消</button>
          <button
            class="btn btn-primary"
            :class="{ loading: isSubmitting }"
            @click="handleSubmit"
          >
            确定
          </button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>

    <!-- 轮回确认对话框 -->
    <dialog ref="reincarnateDialog" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg">确认轮回</h3>
        <p class="py-4">确定要执行轮回吗？此操作不可撤销。</p>
        <div class="modal-action">
          <button class="btn btn-ghost" @click="closeReincarnateDialog">取消</button>
          <button
            class="btn btn-primary"
            :class="{ loading: isReincarnating }"
            @click="confirmReincarnate"
          >
            确定
          </button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { formatDate } from '@/utils/date'

// 六道轮回数据
const realms = [
  { name: '天道', color: '#60a5fa', count: 108 },
  { name: '人道', color: '#34d399', count: 666 },
  { name: '阿修罗道', color: '#f59e0b', count: 72 },
  { name: '畜生道', color: '#8b5cf6', count: 245 },
  { name: '饿鬼道', color: '#ec4899', count: 163 },
  { name: '地狱道', color: '#ef4444', count: 324 },
]

// 状态
const wheelRotation = ref(0)
const currentRealm = ref('人道')
const rotateWheel = (realm: string) => {
  const index = realms.findIndex(r => r.name === realm)
  if (index !== -1) {
    wheelRotation.value = -index * 60
    currentRealm.value = realm
  }
}

interface Soul {
  id: string
  previousLife: string
  merit: number
  nextRealm: string
  status: string
}

interface Record {
  id: string
  soulId: string
  previousLife: string
  nextLife: string
  time: string
  operator: string
  status: string
}

const souls = ref<Soul[]>([
  {
    id: 'SOUL001',
    previousLife: '张三',
    merit: 75,
    nextRealm: '人道',
    status: 'pending',
  },
  {
    id: 'SOUL002',
    previousLife: '李四',
    merit: 95,
    nextRealm: '天道',
    status: 'processing',
  },
  {
    id: 'SOUL003',
    previousLife: '王五',
    merit: 30,
    nextRealm: '饿鬼道',
    status: 'pending',
  },
])

const records = ref<Record[]>([
  {
    id: 'REC001',
    soulId: 'SOUL001',
    previousLife: '张三',
    nextLife: '李四',
    time: '2024-01-15T12:00:00Z',
    operator: '判官王',
    status: 'success',
  },
  {
    id: 'REC002',
    soulId: 'SOUL002',
    previousLife: '王五',
    nextLife: '赵六',
    time: '2024-01-15T11:30:00Z',
    operator: '黑无常',
    status: 'success',
  },
])

const currentPage = ref(1)
const total = ref(100)
const totalPages = ref(10)

// 表单
const editDialog = ref<HTMLDialogElement | null>(null)
const reincarnateDialog = ref<HTMLDialogElement | null>(null)
const isEdit = ref(false)
const isSubmitting = ref(false)
const isReincarnating = ref(false)
const selectedSoul = ref<Soul | null>(null)

interface Form {
  soulId: string
  previousLife: string
  merit: number
  nextRealm: string
}

interface FormErrors {
  soulId: string
  previousLife: string
  merit: string
  nextRealm: string
}

const form = reactive<Form>({
  soulId: '',
  previousLife: '',
  merit: 0,
  nextRealm: '',
})

const errors = reactive<FormErrors>({
  soulId: '',
  previousLife: '',
  merit: '',
  nextRealm: '',
})

// 方法
const getRealmBadgeClass = (realm: string) => {
  switch (realm) {
    case '天道':
      return 'badge-primary'
    case '人道':
      return 'badge-success'
    case '阿修罗道':
      return 'badge-warning'
    case '畜生道':
      return 'badge-secondary'
    case '饿鬼道':
      return 'badge-accent'
    case '地狱道':
      return 'badge-error'
    default:
      return 'badge-ghost'
  }
}

const getStatusBadgeClass = (status: string) => {
  switch (status) {
    case 'success':
      return 'badge-success'
    case 'pending':
      return 'badge-warning'
    case 'processing':
      return 'badge-info'
    case 'failed':
      return 'badge-error'
    default:
      return 'badge-ghost'
  }
}

const getStatusLabel = (status: string) => {
  switch (status) {
    case 'success':
      return '成功'
    case 'pending':
      return '待处理'
    case 'processing':
      return '处理中'
    case 'failed':
      return '失败'
    default:
      return '未知'
  }
}

const handleNewReincarnation = () => {
  isEdit.value = false
  form.soulId = ''
  form.previousLife = ''
  form.merit = 0
  form.nextRealm = ''
  Object.keys(errors).forEach(key => {
    errors[key as keyof FormErrors] = ''
  })
  editDialog.value?.showModal()
}

const handleEdit = (soul: Soul) => {
  isEdit.value = true
  selectedSoul.value = soul
  form.soulId = soul.id
  form.previousLife = soul.previousLife
  form.merit = soul.merit
  form.nextRealm = soul.nextRealm
  Object.keys(errors).forEach(key => {
    errors[key as keyof FormErrors] = ''
  })
  editDialog.value?.showModal()
}

const handleReincarnate = (soul: Soul) => {
  selectedSoul.value = soul
  rotateWheel(soul.nextRealm)
  reincarnateDialog.value?.showModal()
}

const validateForm = () => {
  let isValid = true
  if (!form.soulId) {
    errors.soulId = '请输入魂魄ID'
    isValid = false
  }
  if (!form.previousLife) {
    errors.previousLife = '请输入前世'
    isValid = false
  }
  if (!form.merit || form.merit < 0 || form.merit > 100) {
    errors.merit = '请输入0-100之间的功德值'
    isValid = false
  }
  if (!form.nextRealm) {
    errors.nextRealm = '请选择待转生道'
    isValid = false
  }
  return isValid
}

const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  isSubmitting.value = true
  try {
    // TODO: 调用保存 API
    await new Promise(resolve => setTimeout(resolve, 2000))
    console.log('Save form:', form)
    closeDialog()
  } finally {
    isSubmitting.value = false
  }
}

const confirmReincarnate = async () => {
  if (!selectedSoul.value) return

  isReincarnating.value = true
  try {
    // TODO: 调用轮回 API
    await new Promise(resolve => setTimeout(resolve, 2000))
    console.log('Reincarnate soul:', selectedSoul.value)
    closeReincarnateDialog()
  } finally {
    isReincarnating.value = false
  }
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  // TODO: 调用分页 API
  console.log('Change page to:', page)
}

const closeDialog = () => {
  editDialog.value?.close()
}

const closeReincarnateDialog = () => {
  reincarnateDialog.value?.close()
}
</script>

<style scoped>
.radial-progress {
  --thickness: 2px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}
</style>
